const fs = require('fs')
const prompt = require('./inquier')
const downloadCode = require('./download')
const {copyFile, removeDir} = require('./files')
const ejs = require('ejs')
const getPath = require('./paths')

const createApp = async (source) => {
    // 删除临时文件夹
    const tmpDir = getPath('.tmp');
    removeDir(tmpDir)
    // 与用户交互获取答案
    const answer = await prompt();
    const projectType = 'vue';
    // 下载项目保存到临时文件夹下
    const result = await downloadCode(projectType, tmpDir)
    if (result.state === 'success') {
        const fileUrl = `${tmpDir}/${projectType}`
        const files = fs.readdirSync(fileUrl);
        files.forEach(fileName => {
            if (/.(json|js)/.test(fileName)) {
                const content = fs.readFileSync(`${fileUrl}/${fileName}`, 'utf-8');
                const newContent = ejs.render(content, answer)
                fs.writeFileSync(`${fileUrl}/${fileName}`, newContent)
            }
           
        });
        const res = await copyFile(`${tmpDir}/${projectType}`, answer.projectname);
        if (res && res.state === 'success') {
            console.log('拷贝文件成功！')
            removeDir(tmpDir)
            console.log('删除临时文件成功！')
        }
    }
}

module.exports = {createApp};